//建栅栏
function currentTotalFencesCost() {
    var totalFences = 0;
    window.myData.currentPasture.forEach(element => {
        totalFences += element.deltaFencesNum;
    });

    return totalFences;
}

function updateCurrentTotalFencesCost() {    
    $("#building-Fences-additional-prompt").text(`当前已使用${currentTotalFencesCost()}根栅栏`);
}

function updateFenceForCell(currentCell, neighborCell, direction) {
    // neighborCell == null 代表是边缘
    // neighborCell.pastureIndex == null 表示相邻的单元格不是牧场
    // neighborCell.pastureIndex > pastureIndex 表示相邻单元格是不同的牧场，栅栏总是显示在牧场编号小的这一侧，相等表示是同一个牧场也不显示
    var currentCellNode = getCellNode(currentCell.x, currentCell.y);
    if (currentCell.pastureIndex != null ) {
        if (neighborCell == null || neighborCell.pastureIndex == null || neighborCell.pastureIndex > currentCell.pastureIndex) {
            currentCellNode.css(`border-${direction}`, "solid 4px #03C16099");
            return;
        }
    }
        
    currentCellNode.css(`border-${direction}`, "dotted 1px #3f3f3f");
    
}

window.updatePastures = function () {
    var cells = window.myData.farmCells;
    var gridHeight = cells[0].length;
    var gridWidth = cells.length;

    for (let x = 0; x < gridWidth; x++) {
        for (let y = 0; y < gridHeight; y++) {
            var e = cells[x][y];
            // console.log(`${x} ${y}`);

            if (e.pastureIndex != null) {
                console.log("1");
            }

            // 上
            updateFenceForCell(e, y > 0 ? cells[x][y - 1] : null, "top");
            // 右
            updateFenceForCell(e, x < gridWidth - 1 ? cells[x + 1][y] : null, "right");
            // 下
            updateFenceForCell(e, y < gridHeight - 1 ? cells[x][y + 1] : null, "bottom");
            // 左
            updateFenceForCell(e, x > 0 ? cells[x - 1][y] : null, "left");
        }
    }
}

function calculateDeltaFences(cells, x, y, newPastureIndex) {
    // 初始栅栏数量
    let fencesNeeded = 4;

    // 检查上方单元格
    if (y > 0 && cells[x][y - 1] != null && cells[x][y - 1].pastureIndex != null) {
        if (cells[x][y - 1].pastureIndex < newPastureIndex) {
            fencesNeeded -= 1;
        } else if (cells[x][y - 1].pastureIndex === newPastureIndex) {
            fencesNeeded -= 2;
        }
    }

    // 检查右方单元格
    if (x < cells.length - 1 && cells[x + 1][y] != null && cells[x + 1][y].pastureIndex != null) {
        if (cells[x + 1][y].pastureIndex < newPastureIndex) {
            fencesNeeded -= 1;
        } else if (cells[x + 1][y].pastureIndex == newPastureIndex) {
            fencesNeeded -= 2;
        }
    }
    
    // 检查下方单元格
    if (y < cells[0].length - 1 && cells[x][y + 1] != null && cells[x][y + 1].pastureIndex != null) {
        if (cells[x][y + 1].pastureIndex < newPastureIndex) {
            fencesNeeded -= 1;
        } else if (cells[x][y + 1].pastureIndex == newPastureIndex) {
            fencesNeeded -= 2;
        }
    }
    
    // 检查左方单元格
    if (x > 0 && cells[x - 1][y] != null && cells[x - 1][y].pastureIndex != null) {
        if (cells[x - 1][y].pastureIndex < newPastureIndex) {
            fencesNeeded -= 1;
        } else if (cells[x - 1][y].pastureIndex == newPastureIndex) {
            fencesNeeded -= 2;
        }
    }

    // fencesNeeded 为 栅栏改变值，允许为负数
    return fencesNeeded;
}

// (x, y)对应的格子是否与当前牧场相邻
function isAdjacentToCurrentPasture(x, y) {
    const cells = window.myData.farmCells;
    const currentPasture = window.myData.currentPasture;

    return currentPasture.some(cell => {
        return (cell.x === x && Math.abs(cell.y - y) === 1) || 
               (cell.y === y && Math.abs(cell.x - x) === 1);
    });
}

window.selectCellForFenceBuilding = function (cell, x, y) {
    if (cell.building != null && cell.building != "stable") {
        return;
    }

    if (cell.pastureIndex != null) {
        return; // 点击的cell是已有的牧场，忽略该次点击
    }

    if (window.myData.currentPasture.length > 0 && !isAdjacentToCurrentPasture(x, y)) {
        alert("新选中的格子必须与当前牧场的格子相邻。");
        return;
    }

    var pastures = window.myData.pastures;
    var deltaFencesNum = calculateDeltaFences(window.myData.farmCells, x, y, pastures.length);
    console.log(deltaFencesNum);

    cell.pastureIndex = pastures.length;
    cell.deltaFencesNum = deltaFencesNum;

    window.myData.currentPasture.push(cell);
    updateCurrentTotalFencesCost();
    updatePastures();
    updateResourceBar();
}


window.selectBuildingFences = async function () {
    if (!confirm('确定选择"围栏"？')) {
        return;
    }

    var workSpaceKey = "building-Fences";
    await dispatchEvent(EVENT_USE_TURN_ACTION_BEFORE, { workSpaceKey });

    window.actionData.status = "buildingFences";
    initForBuildingFences();

    // 初始化当前行动已使用的格子数
    window.actionData.usedCells = 0;

    updateAdditionalView();

    window.myData.unusedWorker -= 1;
    updateResourceBar();

    appendWorkerToTitle(workSpaceKey);
}

window.initForBuildingFences = function () {
    // 记录剩余栅栏数，以便后续检查本次行动是否建造了栅栏
    window.myData.leftFencesBeforeBuildingFences = window.myData.leftFences;
}

window.undoAddPasture = function () {
    var cell = window.myData.currentPasture.pop();
    if (cell == undefined) {
        return;
    }
    cell.pastureIndex = null;

    updateCurrentTotalFencesCost();
    updatePastures();

    // updateFarm();
    updateResourceBar();
}

window.startAnotherPasture = function () {
    if (window.myData.currentPasture.length == 0) {
        return;
    }
    var cost = currentTotalFencesCost();
    window.myData.wood -= cost;
    window.myData.leftFences -= cost;
    window.actionData.usedCells += window.myData.currentPasture.length;

    window.myData.pastures.push(window.myData.currentPasture);
    window.myData.currentPasture = [];

    updateCurrentTotalFencesCost();
    updateResourceBar();
}

window.endBuildingFences = function () {
    startAnotherPasture();

    endAction();

    dispatchEventFenceBuildingCompleted();
}

window.dispatchEventFenceBuildingCompleted = function () {
    // 如果用户刚刚建造了围栏，则抛出建栅栏结束事件
    if (window.myData.leftFencesBeforeBuildingFences - window.myData.leftFences > 0) {
        // 由于需要让ui先更新，所以此处做了延迟处理。
        dispatchEventDelay(EVENT_FENCE_BUILDING_COMPLETED, { usedCellCount: window.actionData.usedCells });
    }
}